from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from course import models,courseser
from rest_framework.generics import ListAPIView
from rest_framework.pagination import PageNumberPagination
from django.db.models import Q

# Create your views here.
#获取到首页的一级分类以及孩子
class Category(APIView):
    def get(self,request):
        allcate=models.CategoryModel.objects.filter(parent=None,ishome=True,isshow=True).order_by('order')
        ser=courseser.CategorySerializer(allcate,many=True)
        for i in ser.data:
            i['children']=i['children'][:3]
        return Response({"msg":"ok","data":ser.data,"code":200})

#获取到当前的分类
class NowCate(APIView):
    def get(self,request):
        id=request.query_params.get('id')
        info=models.CategoryModel.objects.filter(id=id,parent=None,ishome=True,isshow=True).first()
        ser=courseser.CategorySerializer(info)
        #根据一级分类 拿到对应的二级分类 然后查询推荐的课程并且排序 拿到数据后存储ser.data中
        twocate=models.CategoryModel.objects.filter(parent=id,isshow=True).values_list('id',flat=True)
        course=models.CourseModel.objects.filter(category__in=twocate,isshow=True,ishome=True).order_by('order').values()[:4]
        courseinfo=ser.data
        courseinfo['course']=course
        #ser.data['course']=course
        return Response({"msg":"ok","data":courseinfo,"code":200})
#方向
class Direction(APIView):
    def get(self,request):
        allcate=models.CategoryModel.objects.filter(parent=None,isshow=True).order_by('order')
        ser=courseser.Category(allcate,many=True)
        return Response({"msg":"ok","data":ser.data,"code":200})

#所有的子类以及子类的检索
class ChildCate(APIView):
    def get(self,request):
        pid=int(request.query_params.get('pid'))
        if pid==0:
            child=models.CategoryModel.objects.exclude(parent=None,isshow=False).order_by('order')
            print(child)
        else:
            child=models.CategoryModel.objects.filter(parent=pid,isshow=True).order_by('order')
        ser=courseser.Category(child,many=True)
        return Response({"msg":"ok","data":ser.data,"code":200})

#定义分页类
class CoursePage(PageNumberPagination):
    page_size=3
    page_size_query_param='size'
    page_query_param='page'

#课程列表
class CourseList(ListAPIView):
    queryset=models.CourseModel.objects.all()
    serializer_class=courseser.CourseSerializer
    pagination_class=CoursePage
    def get_queryset(self):#根据条件筛选
        #获取搜索的条件
        direction=int(self.request.query_params.get('direction',0))
        cate=int(self.request.query_params.get('cate',0))
        level=int(self.request.query_params.get('level',0))
        order=self.request.query_params.get('order')
        query=Q()
        #如果有cate 就不用看方向
        if cate!=0:
            query&=Q(category=cate)
        #方向不空 但是 cate为空
        if direction>0 and cate==0:
            #根据方向的id所有的二级分类的id [1,2,3,4] 然后使用in语法检索
            allcate=models.CategoryModel.objects.filter(parent_id=direction).values()
            #print(allcate)
            #allcate=[i['id'] for i in allcate]
            child=[]
            for i in allcate:
                child.append(i['id'])
            query&=Q(category__in=child)
        if level>0:
            query&=Q(level=level)
        if order:
            return self.queryset.filter(query).order_by(order)
        else:
            return self.queryset.filter(query)

#课程响应
class Detail(APIView):
    def get(self,request):
        id=request.query_params.get('id')
        info=models.CourseModel.objects.filter(id=id).first()
        info.read+=1
        info.save()
        ser=courseser.CourseSerializer(info)
        return Response({"msg":"success","code":200,"data":ser.data})

from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.viewsets import ModelViewSet
class Brand(ModelViewSet):
    queryset=models.BrandModel.objects.all()
    serializer_class = courseser.BrandSerializer
    parser_classes = (MultiPartParser, FormParser)
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, headers=headers)
        return Response(serializer.errors)
from rest_framework.generics import GenericAPIView
from django.core.files.storage import default_storage
class Upload(GenericAPIView):
    serializer_class = courseser.BannerImage
    def post(self,request):
        ser=self.get_serializer(data=request.data)
        if ser.is_valid():
            file=ser.validated_data.get('file')
            name=default_storage.save(file.name,file)
            url=default_storage.url(name)
            #print(ser)
            return Response({"msg":"上传成功","url":url})
        else:
            return Response(ser.errors)


#索引搜索视图
from drf_haystack.viewsets import HaystackViewSet
from utils.myredis import redistoll
class HotWordView(HaystackViewSet):
    index_models = [models.CourseModel]
    serializer_class = courseser.CourseIndexSerializer
    pagination_class = CoursePage
    #重写list方法
    def list(self, request, *args, **kwargs):
        text=request.query_params.get('text','')
        if text:
            #记录关键词
            redistoll.hotadd('09ahot',text)
        data=super().list(request, *args, **kwargs).data
        for i in data['results']:
            i['cover']='http://127.0.0.1:8000/uploads'+i['cover']
        return Response(data)

#获取到关键词
class HotWord(APIView):
    def get(self,request):
        data=redistoll.hotget('09ahot',4)
        return Response(data)
